<?php

define('DATA_FILENAME', 'gr_prem.csv');

require_once 'Cron.php';

function test($lpLogoBg, $users) {
	$posBg = array();
	foreach ($lpLogoBg as $value) {
		if (!key_exists($value[0], $users) || !($users[$value[0]] instanceof EmpevalUsers))
			continue;
		$user = $users[$value[0]];
		$position = $user->getUserPositionss()->getFirst()->getPositions();
		
		if (!key_exists($position->getId(), $posBg))
			$posBg[$position->getId()] = array();
		if (!in_array($value[1], $posBg[$position->getId()]))
			$posBg[$position->getId()][] = $value[1];
	}
	$out = array();
	foreach ($posBg as $posId => $groups) {
		if (count($groups) == 1)
			continue;

		$out[$posId] = array();
		foreach ($groups as $group) {
			$out[$posId][] = $group;
		}
	}
	return (empty($out)) ? null : $out;
}

function update($lpLogoBg, $users) {
	$bounsGroups = EmpevalBonusGroupsQuery::create()->find()->getArrayCopy('Code');
	$con = Propel::getConnection('vgp_empeval');
	$con->beginTransaction();
	try {
		EmpevalPositionsQuery::create()->update(array('Grade' => null), $con);
		foreach ($lpLogoBg as $value) {
			if (!key_exists($value[0], $users) || !($users[$value[0]] instanceof EmpevalUsers))
				continue;
			$user = $users[$value[0]];
			$userPositions = $user->getUserPositionss();//->getFirst()->getPositions();
			foreach ($userPositions as $userPosition) {
				$position = $userPosition->getPositions();
				$position->setBonusGroups($bounsGroups[$value[1]]);
				$position->setGrade(16);
				$position->save($con);
			}
		}
		$con->commit();
	} catch (Exception $e) {
		$con->rollBack();
		throw $e;
	}
}

$lpLogoBg = Core_Tools::CsvToArray(dirname(__FILE__) . '/' . DATA_FILENAME, false);
$users = EmpevalUsersQuery::create()
->useUserPositionsQuery()
	->joinPositions()
->endUse()
->addJoinCondition('UserPositions', 'UserPositions.active = 1')
->find()
->getArrayCopy('ExtId');

if (!(isset($argv[1]) && $argv[1] == '/force')) {
	$testResult = test($lpLogoBg, $users);
	if ($testResult != null) {
		var_dump($testResult);
		die;
	}
}

if (!(isset($argv[1]) && $argv[1] == '/test')) {
	update($lpLogoBg, $users);
}
